<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>添加商品</span>
      </div>

      <el-form ref="productForm" :model="productForm" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品编号" prop="productNumber">
              <el-input v-model="productForm.productNumber" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="productForm.sort" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="productForm.brandId" placeholder="请选择品牌" style="width: 100%">
                <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="categoryId">
              <el-cascader v-model="productForm.categoryId" :options="categoryOptions" :props="{ checkStrictly: true }"
                style="width: 100%" placeholder="请选择分类" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="主图" prop="mainPic">
              <SingleUpload :value="productForm.mainPic" @input="handleInputMainPic"></SingleUpload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 状态设置 -->
        <el-divider content-position="left">状态设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="上架状态">
              <el-switch v-model="productForm.publishStatus" :active-value="1" :inactive-value="0" active-text="上架"
                inactive-text="下架" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="新品状态">
              <el-switch v-model="productForm.newStatus" :active-value="1" :inactive-value="0" active-text="是"
                inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="推荐状态">
              <el-switch v-model="productForm.recommandStatus" :active-value="1" :inactive-value="0" active-text="推荐"
                inactive-text="不推荐" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务保证">
              <el-select v-model="productForm.serviceIds" :collapse-tags="true" multiple placeholder="请选择服务"
                style="width: 100%">
                <el-option label="7天无理由退货" value="1" />
                <el-option label="正品保证" value="2" />
                <el-option label="极速退款" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品规格 -->
        <div style="margin-bottom: 10px;">
          <el-divider content-position="left">商品规格</el-divider>
          <el-button type="primary" size="mini" @click="addGroup">添加规格组</el-button>
        </div>
        <div v-for="(group, groupIndex) in productForm.productGroupList" :key="groupIndex" class="group-item">
          <el-card class="box-card" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>规格组 {{ groupIndex + 1 }}</span>
              <el-button v-if="productForm.productGroupList.length > 1" style="float: right; padding: 3px 0" type="text"
                @click="removeGroup(groupIndex)">删除</el-button>
            </div>
                <el-row :gutter="20" style="margin-bottom: 10px;">
          <el-card shadow="never" class="cardBg">
            <div v-for="(productAttr, idx) in group.selectProductAttr" :key="idx" style="margin-bottom: 5px;">
              <span style="font-size: 14px;">{{ productAttr.name }}：</span>
              <el-checkbox-group v-if="productAttr.inputType === 1" v-model="group.selectProductAttr[idx].values">
                <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :label="item" :key="item"
                  class="littleMarginLeft"></el-checkbox>
              </el-checkbox-group>
              <div v-else>
                <el-checkbox-group v-model="group.selectProductAttr[idx].values">
                  <div v-for="(item, index) in group.selectProductAttr[idx].options" :key="index"
                    style="display: inline-block" class="littleMarginLeft">
                    <el-checkbox :label="item" :key="item"></el-checkbox>
                    <el-button type="text" class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx, index)">删除
                    </el-button>
                  </div>
                </el-checkbox-group>
                <el-input size="mini" v-model="productAttr.addProductAttrValue" style="width: 160px;margin-left: 10px"
                  clearable></el-input>
                <el-button size="mini" class="littleMarginLeft" @click="handleAddProductAttrValue(idx,group.selectProductAttr,productAttr)">增加</el-button>
              </div>
            </div>
            <el-button @click="refreshSku(groupIndex,group.selectProductAttr)" type="success" size="mini">刷新SKU列表</el-button>
          </el-card>
        </el-row>
            <el-row :gutter="20">
                  <el-col :span="8">
            <el-form-item label="属性类型"   :rules="{ required: true, message: '请选择属性类型', trigger: 'change' }" :prop="`productGroupList.${groupIndex}.attributeCategoryId`">
              <el-select @change="handleProductAttrChange(group.attributeCategoryId,groupIndex)" v-model="group.attributeCategoryId"
                placeholder="请选择属性类型" style="width: 100%">
                <el-option v-for="item in attributeCategoryOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
              <el-col :span="8">
                <el-form-item :prop="`productGroupList.${groupIndex}.name`" label="规格名称"
                  :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }">
                  <el-input v-model="group.name" placeholder="请输入规格名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item :prop="`productGroupList.${groupIndex}.album`" label="规格图片">
              <multi-upload v-model="group.album"></multi-upload>
            </el-form-item>
            <el-form-item label="商品详情">
              <tinymce :width="595" :height="300" v-model="group.detail"></tinymce>
            </el-form-item>
            <!-- SKU库存列表 -->
            <el-divider content-position="left">SKU库存 </el-divider>
            <div  class="sku-item">
              <el-card style="margin-bottom: 10px" class="box-card" shadow="never">
                <div slot="header" class="clearfix">
                  <!-- <span>SKU {{ skuIndex + 1 }}</span> -->
                  <el-button v-if="group.skuStockList.length > 1" style="float: right; padding: 3px 0" type="text"
                    @click="removeSku(groupIndex, skuIndex)">删除</el-button>
                </div>
           <el-table style="width: 100%;margin-top: 20px"
                  :data="group.skuStockList"
                  border>
          <el-table-column
            v-for="(item,index) in group.selectProductAttr"
            :label="item.name"
            :key="item.id"
            align="center">
            <template slot-scope="scope">
              {{getProductSkuSp(scope.row,index)}}
            </template>
          </el-table-column>
          <el-table-column
            label="销售价格"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="促销价格"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.promotionPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="商品库存"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存预警值"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowStock"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="SKU编号"
            width="160"
            align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="促销类型"
            min-width="260"
            align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.promotionType" @change="handlePromotionTypeChange(scope.row)" placeholder="请选择" size="mini">
                    <el-option label="无促销" :value="0" />
                    <el-option label="阶梯价格" :value="1" />
                    <el-option label="满减价格" :value="2" />
              </el-select>
              <el-button v-if="scope.row.promotionType===1" @click="handleAddProductSkuLadder(scope.row)" type="primary" size="mini">增加阶梯价格</el-button>
              <el-button v-if="scope.row.promotionType===2" @click="handleAddProductSkuFullReduction(scope.row)" type="primary" size="mini">增加满减价格</el-button>
              <div v-if="scope.row.promotionType===1" class="sku-item">
                 <div v-for="(ladder, ladderIndex) in scope.row.productLadderList" :key="ladderIndex" class="ladder-item">
                    <el-row :gutter="20">
                      <el-col :span="8">
                          数量
                          <el-input v-model="ladder.count" :min="1" style="width: 100%" />
                      </el-col>
                      <el-col :span="8">
                        折扣
                        <el-input v-model="ladder.discount" :min="0" :max="1" :precision="2" style="width: 100%" />
                      </el-col>
                      <el-col :span="8">
                        <el-button v-if="scope.row.productLadderList.length > 1" type="danger" icon="el-icon-delete"
                          @click="removeLadder( scope.row, ladderIndex)" />
                      </el-col>
                    </el-row>
                  </div>
              </div>
              <div  v-if="scope.row.promotionType===2" class="sku-item" >
                 <div v-for="(reduction, reductionIndex) in scope.row.productFullReductionList" :key="reductionIndex"
                    class="reduction-item">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        满金额
                          <el-input v-model="reduction.fullPrice" :min="0" :precision="2" style="width: 100%" />
                      </el-col>
                      <el-col :span="8">
                        减金额
                          <el-input v-model="reduction.reducePrice" :min="0" :precision="2" style="width: 100%" />
                      </el-col>
                      <el-col :span="8">
                        <el-button v-if="scope.row.productFullReductionList.length > 1" type="danger" icon="el-icon-delete"
                          @click="removeReduction( scope.row, reductionIndex)" />
                      </el-col>
                    </el-row>
                  </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleRemoveProductSku(scope.$index, scope.row,groupIndex)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
<!--
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.skuCode`"
                      label="SKU编码" :rules="{ required: true, message: '请输入SKU编码', trigger: 'blur' }">
                      <el-input v-model="sku.skuCode" placeholder="SKU编码" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.keywords`"
                      label="关键词">
                      <el-input v-model="sku.keywords" placeholder="关键词" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.price`" label="价格"
                      :rules="{ required: true, message: '请输入价格', trigger: 'blur' }">
                      <el-input v-model="sku.price" :min="0" :precision="2" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.stock`" label="库存"
                      :rules="{ required: true, message: '请输入库存', trigger: 'blur' }">
                      <el-input v-model="sku.stock" :min="0" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.length`"
                      label="长度(cm)">
                      <el-input v-model="sku.length" :min="0" :precision="2" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.width`"
                      label="宽度(cm)">
                      <el-input v-model="sku.width" :min="0" :precision="2" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.height`"
                      label="高度(cm)">
                      <el-input v-model="sku.height" :min="0" :precision="2" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.weight`"
                      label="重量(kg)">
                      <el-input v-model="sku.weight" :min="0" :precision="2" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.lowStock`"
                      label="低库存预警">
                      <el-input v-model="sku.lowStock" :min="0" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.promotionType`"
                      label="促销类型">
                      <el-select v-model="sku.promotionType" placeholder="请选择" style="width: 100%">
                        <el-option label="无促销" :value="0" />
                        <el-option label="阶梯价格" :value="1" />
                        <el-option label="满减价格" :value="2" />
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                <!-- </el-row> -->

                <!-- 阶梯价格 -->
                <!-- <template v-if="sku.promotionType == 1">
                  <el-divider content-position="left">阶梯价格</el-divider>
                  <el-button type="text" size="small" @click="addLadder(groupIndex, skuIndex)">添加阶梯价格</el-button>
                  <div v-for="(ladder, ladderIndex) in sku.productLadderList" :key="ladderIndex" class="ladder-item">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item
                          :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.productLadderList.${ladderIndex}.count`"
                          label="数量">
                          <el-input v-model="ladder.count" :min="1" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item
                          :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.productLadderList.${ladderIndex}.discount`"
                          label="折扣">
                          <el-input v-model="ladder.discount" :min="0" :max="1" :precision="2" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-button v-if="sku.productLadderList.length > 1" type="danger" icon="el-icon-delete"
                          @click="removeLadder(groupIndex, skuIndex, ladderIndex)" />
                      </el-col>
                    </el-row>
                  </div>
                </template> -->
                <!-- <template v-if="sku.promotionType == 2">
                  <el-divider content-position="left">满减价格</el-divider>
                  <el-button type="text" size="small" @click="addReduction(groupIndex, skuIndex)">添加满减价格</el-button>
                  <div v-for="(reduction, reductionIndex) in sku.productFullReductionList" :key="reductionIndex"
                    class="reduction-item">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item
                          :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.productFullReductionList.${reductionIndex}.fullPrice`"
                          label="满金额">
                          <el-input v-model="reduction.fullPrice" :min="0" :precision="2" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item
                          :prop="`productGroupList.${groupIndex}.skuStockList.${skuIndex}.productFullReductionList.${reductionIndex}.reducePrice`"
                          label="减金额">
                          <el-input v-model="reduction.reducePrice" :min="0" :precision="2" style="width: 100%" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-button v-if="sku.productFullReductionList.length > 1" type="danger" icon="el-icon-delete"
                          @click="removeReduction(groupIndex, skuIndex, reductionIndex)" />
                      </el-col>
                    </el-row>
                  </div>
                </template> -->
              </el-card>
            </div>
          </el-card>
        </div>
        <!-- 操作按钮 -->
        <el-form-item style="margin-top: 20px">
          <el-button type="primary" @click="submitForm">保存商品</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { fetchListWithChildren } from '@/api/productCate'
import { fetchList as fetchProductAttrCateList } from '@/api/productAttrCate'
import { fetchList as fetchProductAttrList } from '@/api/productAttr'
import { createProduct } from '@/api/product'
import { fetchList as fetchBrandList } from '@/api/brand'
import SingleUpload from '@/components/Upload/singleUpload'
import MultiUpload from '@/components/Upload/multiUpload'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'AddProduct',
  components: { SingleUpload, MultiUpload, Tinymce },
  data() {
    return {
      selectProductAttr: [],
      addProductAttrValue: "",
      productForm: {
        brandId: null,
        categoryId: null,
        attributeCategoryId: null,
        productNumber: '',
        name: '',
        mainPic: '',
        sort: 0,
        publishStatus: 0,
        newStatus: 0,
        recommandStatus: 0,
        serviceIds: '1',
        productGroupList: [
          {
            name: '',
            detail: '',
            album: [],
            skuStockList: [
              {
                skuCode: '',
                keywords: '',
                price: 0,
                length: 0,
                width: 0,
                height: 0,
                weight: 0,
                stock: 0,
                lowStock: 0,
                promotionType: 0,
                spData: '',
                productLadderList: [
                  {
                    count: 1,
                    discount: 1
                  }
                ],
                productFullReductionList: [
                  {
                    fullPrice: 0,
                    reducePrice: 0
                  }
                ]
              }
            ]
          }
        ]
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        productNumber: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        // attributeCategoryId: [{ required: true, message: '请选择属性类型', trigger: 'change' }]
      },
      skuList: [],
      brandOptions: [],
      categoryOptions: [],
      attributeCategoryOptions: [],
      uploadUrl: '/api/oss/upload' // 上传接口地址
    }
  },
  created() {
    this.loadBrandOptions()
    this.loadCategoryOptions()
    this.getProductAttrCateList()
  },
  methods: {
    handlePromotionTypeChange(row){
      row.productLadderList = []
      row.productFullReductionList = []
      console.log("促销类型", row)
    },
    handleAddProductSkuFullReduction(row){
       row.productFullReductionList.push({
        fullPrice: 0,
        reducePrice: 0
      })
    },
    handleAddProductSkuLadder(row){
      row.productLadderList.push({
        count: 1,
        discount: 1
      })
    },
    // 加载品牌选项
    loadBrandOptions() {
      // 这里应该从API获取品牌列表
      fetchBrandList({ pageNum: 1, pageSize: 100 }).then(response => {
        this.brandOptions = [];
        let brandList = response.data.list;
        for (let i = 0; i < brandList.length; i++) {
          this.brandOptions.push({ label: brandList[i].name, value: brandList[i].id });
        }
      });
    },
    //属性类型
    getProductAttrCateList() {
      let param = { pageNum: 1, pageSize: 100 };
      fetchProductAttrCateList(param).then(response => {
        console.log("属性类型", response)
        this.attributeCategoryOptions = [];
        let list = response.data.list;
        for (let i = 0; i < list.length; i++) {
          this.attributeCategoryOptions.push({ label: list[i].name, value: list[i].id });
        }
      });
    },
    // 加载分类选项
    loadCategoryOptions() {
      // 这里应该从API获取分类树
      fetchListWithChildren().then(response => {
        let list = response.data;
        this.categoryOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ label: list[i].children[j].name, value: list[i].children[j].id });
            }
          }
          this.categoryOptions.push({ label: list[i].name, value: list[i].id, children: children });
        }
      });
    },
      handleRemoveProductSku(index, row,groupIndex) {
        console.log("handleRemoveProductSku",index,row,groupIndex);
          this.productForm.productGroupList[groupIndex].skuStockList.splice(index, 1);
        // delete this.productForm.productSkuList[index];
      },
    handleInputMainPic(url) {
      this.productForm.mainPic = url;
    },
    handleProductAttrChange(value,index) {
      console.log("handleProductAttrChange",value,index)
      this.getProductAttrList(0, value,index);
    },
    handleAddProductAttrValue(idx,arr,item) {
      let options = arr[idx].options;
      if (item.addProductAttrValue == null || item.addProductAttrValue == '') {
        this.$message({
          message: '属性值不能为空',
          type: 'warning',
          duration: 1000
        });
        return
      }
      if (options.indexOf(item.addProductAttrValue) !== -1) {
        this.$message({
          message: '属性值不能重复',
          type: 'warning',
          duration: 1000
        });
        return;
      }
      arr[idx].options.push(item.addProductAttrValue);
      item.addProductAttrValue = null;
    },
    handleRemoveProductAttrValue(idx, index) {
      this.selectProductAttr[idx].options.splice(index, 1);
    },
    refreshSku(index,arr) {
      console.log("refreshSku",index)
      this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.refreshProductSkuList(index,arr);
      });
    },
    refreshProductSkuList(index,arr) {
      console.log("refreshProductSkuList",index,arr)
      let skuList = []
      //只有一个属性时
      if (arr.length === 1) {
        let attr = arr[0];
        for (let i = 0; i < attr.values.length; i++) {
          skuList.push({
            spData: JSON.stringify([{ key: attr.name, value: attr.values[i] }])
          });
        }
      } else if (arr.length === 2) {
        let attr0 = arr[0];
        let attr1 = arr[1];
        for (let i = 0; i < attr0.values.length; i++) {
          if (attr1.values.length === 0) {
            skuList.push({
              spData: JSON.stringify([{ key: attr0.name, value: attr0.values[i] }])
            });
            continue;
          }
          for (let j = 0; j < attr1.values.length; j++) {
            let spData = [];
            spData.push({ key: attr0.name, value: attr0.values[i] });
            spData.push({ key: attr1.name, value: attr1.values[j] });
            skuList.push({
              spData: JSON.stringify(spData)
            });
          }
        }
      } else {
        let attr0 = arr[0];
        let attr1 = arr[1];
        let attr2 =arr[2];
        for (let i = 0; i < attr0.values.length; i++) {
          if (attr1.values.length === 0) {
            skuList.push({
              spData: JSON.stringify([{ key: attr0.name, value: attr0.values[i] }])
            });
            continue;
          }
          for (let j = 0; j < attr1.values.length; j++) {
            if (attr2.values.length === 0) {
              let spData = [];
              spData.push({ key: attr0.name, value: attr0.values[i] });
              spData.push({ key: attr1.name, value: attr1.values[j] });
              skuList.push({
                spData: JSON.stringify(spData)
              });
              continue;
            }
            for (let k = 0; k < attr2.values.length; k++) {
              let spData = [];
              spData.push({ key: attr0.name, value: attr0.values[i] });
              spData.push({ key: attr1.name, value: attr1.values[j] });
              spData.push({ key: attr2.name, value: attr2.values[k] });
              skuList.push({
                spData: JSON.stringify(spData)
              });
            }
          }
        }
      }
      const _sku = {
        skuCode: '',
        keywords: '',
        price: 0,
        length: 0,
        width: 0,
        height: 0,
        weight: 0,
        stock: 0,
        lowStock: 0,
        promotionType: 0,
        spData: '',
        productLadderList: [
          {
            count: 1,
            discount: 1
          }
        ],
        productFullReductionList: [
          {
            fullPrice: 0,
            reducePrice: 0
          }
        ]
      }
      skuList = skuList.map(item => ({ ..._sku, ...item }));
       this.$set(this.productForm.productGroupList[index], 'skuList', []);
       this.$set(this.productForm.productGroupList[index], 'skuStockList', skuList);
      // this.productForm.productGroupList[index].skuStockList = skuList;
      console.log("skuList", skuList)
      console.log("this.productForm.productGroupList", this.productForm.productGroupList)
      // this.productForm.productGroupList.forEach(item => {
      //   item.skuStockList = skuList;
      // })
    },
    getProductAttrList(type, cid,index) {
      let param = { pageNum: 1, pageSize: 100, type: type };
      fetchProductAttrList(cid, param).then(response => {
        let list = response.data.list;
        if (type === 0) {
          this.$set(this.productForm.productGroupList[index], 'selectProductAttr', []);
          for (let i = 0; i < list.length; i++) {
            let options = [];
            let values = [];
            if (this.isEdit) {
              if (list[i].handAddStatus === 1) {
                //编辑状态下获取手动添加编辑属性
                options = this.getEditAttrOptions(list[i].id);
              }
              //编辑状态下获取选中属性
              values = this.getEditAttrValues(i);
            }
            this.productForm.productGroupList[index].selectProductAttr.push({
              id: list[i].id,
              name: list[i].name,
              handAddStatus: list[i].handAddStatus,
              inputList: list[i].inputList,
              inputType:list[i].inputType,
              values: values,
              options: options
            });
          }
          if (this.isEdit) {
            //编辑模式下刷新商品属性图片
            this.refreshProductAttrPics();
          }
        } else {
          // this.selectProductParam = [];
          // for (let i = 0; i < list.length; i++) {
          //   let value = null;
          //   if (this.isEdit) {
          //     //编辑模式下获取参数属性
          //     value = this.getEditParamValue(list[i].id);
          //   }
          //   this.selectProductParam.push({
          //     id: list[i].id,
          //     name: list[i].name,
          //     value: value,
          //     inputType: list[i].inputType,
          //     inputList: list[i].inputList
          //   });
          // }
        }
      });
    },
     getProductSkuSp(row, index) {
        if(row.spData){
           let spData = JSON.parse(row.spData);
        if(spData!=null&&index<spData.length){
          return spData[index].value;
        }else{
          return null;
        }
        }

      },
    // 添加规格组
    addGroup() {
      this.productForm.productGroupList.push({
        name: '',
        detail: '',
        album: [],
        skuStockList: [
          {
            skuCode: '',
            keywords: '',
            price: 0,
            length: 0,
            width: 0,
            height: 0,
            weight: 0,
            stock: 0,
            lowStock: 0,
            promotionType: 0,
            spData: '',
            productLadderList: [
              {
                count: 1,
                discount: 1
              }
            ],
            productFullReductionList: [
              {
                fullPrice: 0,
                reducePrice: 0
              }
            ]
          }
        ]
      })
    },

    // 删除规格组
    removeGroup(index) {
      this.productForm.productGroupList.splice(index, 1)
    },

    // 添加SKU
    addSku(groupIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList.push({
        skuCode: '',
        keywords: '',
        price: 0,
        length: 0,
        width: 0,
        height: 0,
        weight: 0,
        stock: 0,
        lowStock: 0,
        promotionType: 0,
        spData: '',
        productLadderList: [
          {
            count: 1,
            discount: 1
          }
        ],
        productFullReductionList: [
          {
            fullPrice: 0,
            reducePrice: 0
          }
        ]
      })
    },
    getInputListArr(inputList) {
      return inputList.split(',');
    },
    // 删除SKU
    removeSku(groupIndex, skuIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList.splice(skuIndex, 1)
    },

    // 添加阶梯价格
    addLadder(groupIndex, skuIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList[skuIndex].productLadderList.push({
        count: 1,
        discount: 1
      })
    },

    // 删除阶梯价格
    removeLadder(row, ladderIndex) {
       console.log("row",row)
      row.productLadderList.splice(ladderIndex, 1)
    },

    // 添加满减价格
    addReduction(groupIndex, skuIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList[skuIndex].productFullReductionList.push({
        fullPrice: 0,
        reducePrice: 0
      })
    },

    // 删除满减价格
    removeReduction(row, reductionIndex) {
      console.log("row",row)
      row.productFullReductionList.splice(reductionIndex, 1)
    },

    // 主图上传成功
    handleMainPicSuccess(res) {
      this.productForm.mainPic = res.data.url
    },

    // 相册上传成功
    handleAlbumSuccess(res, groupIndex) {
      this.productForm.productGroupList[groupIndex].album = res.data.url
    },

    // 上传前验证
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 提交表单
    submitForm() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          // 处理categoryId，如果是数组取最后一个值
          const categoryId = Array.isArray(this.productForm.categoryId)
            ? this.productForm.categoryId[this.productForm.categoryId.length - 1]
            : this.productForm.categoryId
          this.productForm.productGroupList.forEach(item => {
            item.album = item.album.join(',')
          })
          const formData = {
            ...this.productForm,
            categoryId: categoryId
          }
          formData.serviceIds = formData.serviceIds.join(',')
          console.log("formData", this.formData)
          createProduct(formData).then(response => {
            this.$message.success('商品添加成功')
            this.$router.push('/pms/product')
          }).catch(error => {
            this.$message.error('商品添加失败：' + error.message)
          })
        } else {
          this.$message.error('请完善表单信息')
          return false
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.productForm.resetFields()
      this.productForm.productGroupList = [{
        name: '',
        detail: '',
        album: [],
        skuStockList: [{
          skuCode: '',
          keywords: '',
          price: 0,
          length: 0,
          width: 0,
          height: 0,
          weight: 0,
          stock: 0,
          lowStock: 0,
          promotionType: 0,
          spData: '',
          productLadderList: [{ count: 1, discount: 1 }],
          productFullReductionList: [{ fullPrice: 0, reducePrice: 0 }]
        }]
      }]
    }
  }
}
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.cardBg {
  background: #F8F9FC;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.group-item {
  margin-bottom: 20px;
}

.sku-item {
  margin: 10px 0;
}

.ladder-item,
.reduction-item {
  margin-bottom: 10px;
}
</style>
